const osubmit = document.getElementById("tel");
const opassword = document.getElementById("password");
const otel = document.getElementById("username");

osubmit.onclick = function(){
     ajax("http://localhost:3000/api", function(res){
          console.log(res);
        res = JSON.parse(res);
        if(res.code === 0){
            alert("用户名不存在，滚去注册");
            location.href = "../register.html";
        }else if(res.code === 1){
        
            localStorage.setItem("isLogin","ok");
            console.log(localStorage.getItem("isLogin"));
            localStorage.setItem("username",res.data)

            if(confirm("登陆成功，是否跳转到首页")){
                location.href = "../index.html";
            }
        }else if(res.code === 2){
            alert("密码错误，请重新输入");
            opassword.value = "";
            opassword.focus();
        }
     },{
          type:"login",
          username:otel.value,
          password:opassword.value
     })
}





function ajax(url, callback, data){
     let str = "";
     for(let i in data){
          str += `${i}=${data[i]}&`
     }
     url += "?" + str;
     const xhr = new XMLHttpRequest();
     xhr.open("get", url)
     xhr.onload = function(){
          if(xhr.status === 200){
               callback(xhr.responseText)
          }
     }
     xhr.send();
}